﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Store.WP7.Data;
using Store.WP7.Framework;
using Store.WP7.Framework.Helpers;

namespace Store.WP7.ViewModels
{
    public class OrderDetailsPageViewModel : PageViewModelBase
    {
        private readonly StoreService _storeService;
        private int _orderId = 0;
        private bool _orderIsLoaded;
        private OrderViewModel _orderViewModel;
        public OrderViewModel OrderViewModel
        {
            get { return _orderViewModel; }
            set
            {
                _orderViewModel = value;
                RaisePropertyChanged(() => OrderViewModel);
            }
        }

        private string _pageTitle;
        public string PageTitle
        {
            get { return _pageTitle; }
            set
            {
                _pageTitle = value;
                RaisePropertyChanged(() => PageTitle);
            }
        }

        public OrderDetailsPageViewModel()
        {
            _storeService = new StoreService();
        }

        public override void OnNavigatedTo(System.Windows.Navigation.NavigationService navigationService, System.Windows.Navigation.NavigationContext navigationContext, System.Collections.Generic.IDictionary<string, object> state, System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(navigationService, navigationContext, state, e);

            if (!NavigationContext.QueryString.ContainsKey("orderId") || !int.TryParse(NavigationContext.QueryString["orderId"].ToString(), out _orderId))
            {
                NavigationService.GoBack();
                return;
            }
        }

        public override void OnLoaded()
        {
            base.OnLoaded();

            PageTitle = string.Format("commande #{0}", _orderId);

            if (_orderId != 0 && !_orderIsLoaded)
            {
                LoadOrder();
            }
        }

        private void LoadOrder()
        {
            if (!IsBusy)
            {
                IsBusy = true;
                BusyMessage = "chargement de la commande...";
                _storeService.LoadOrderAsync(_orderId, serviceResult =>
                {
                    if (serviceResult.Error == null)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            OrderViewModel = new OrderViewModel(serviceResult.Result);
                            IsBusy = false;
                            BusyMessage = "";
                        });

                        _orderIsLoaded = true;
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            IsBusy = false;
                            ToastService.Instance.ShowNotification(ToastType.Error, "Oops, pas de connexion aux données");
                        });
                    }
                });
            }
        }

        public void Pin()
        {
            string url = string.Format("/Views/OrderDetailsPage.xaml?orderId={0}", _orderId);
            if (!TileHelper.TileExists(url))
            {
                Grid front = CreateFrontGrid();
                Grid back = CreateBackGrid();
                TileHelper.PinOrUdpateUIElement(url, string.Format("commande #{0}", _orderId), 0, front, string.Empty, _orderViewModel.State, back);
            }
        }

        private Grid CreateBackGrid()
        {
            Grid back = new Grid();
            back.Background = new SolidColorBrush(Colors.Orange);
            back.Width = 173;
            back.Height = 173;

            TextBlock textBlock = new TextBlock();
            textBlock.FontSize = 35;
            textBlock.TextAlignment = TextAlignment.Right;
            textBlock.HorizontalAlignment = HorizontalAlignment.Right;
            textBlock.VerticalAlignment = VerticalAlignment.Bottom;
            textBlock.Margin = new Thickness(20,10,10,5);
            textBlock.Text = string.Format("{0} / 3", _orderViewModel.InnerOrder.State);

            back.Children.Add(textBlock);

            return back;
        }

        private Grid CreateFrontGrid()
        {
            Grid front = new Grid();
            front.Width = 173;
            front.Height = 173;

            Image image = new Image();
            image.Source = new BitmapImage(new Uri("/icons/tile.png", UriKind.Relative));
            image.Width = 173;
            image.Height = 173;

            front.Children.Add(image);

            return front;
        }

        public void Unpin()
        {
            string url = string.Format("/Views/OrderDetailsPage.xaml?orderId={0}", _orderId);
            TileHelper.Unpin(url);
        }

        public void Refresh()
        {
            _orderIsLoaded = false;
            LoadOrder();
        }
    }
}
